import materialreqbillsApi from '../../../common/api/cbs/materialreqbills.api.js';
import doT from '../../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { Select2Info, Select2Page } from "../../../common/serve-request.js";

let _vm, conumingInfo = []
const addsaleTemplate = doT.template($('#addmatrrialreq-template').text());
(function (window, document, $) {
    $(async function () {
        _vm = new Vue({
            el: "#addmatrrialreq-form",
            data() {
                return {
                    "bizDate": moment(new Date()).format('YYYY-MM-DD'),
                    "storageOrgUnit": {
                        "id": "",
                        "name": "",
                        "code": ""
                    },
                    "warehouse": {
                        "id": "",
                        "name": "",
                        "code": ""
                    },
                    "inStorageOrgUnit": {
                        "id": "",
                        "name": "",
                        "code": ""
                    },
                    "inWarehouse": {
                        "id": "",
                        "name": "",
                        "code": ""
                    },
                    "breedBatch": {
                        "id": "",
                        "name": ""
                    },
                    "bType": null,
                    "remark": "",
                    "entries": [],
                    "idup": "",
                    "isShowAddEntry": true,
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                if (params.id) {
                    document.title = '物料领用 - 编辑'
                }
            },

        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        clickFun()   // 领用类型
        // 初始化 获取部门数据
        await materialreqbillsApi.queryBaseOrgunitList('ooca', 1, 210).then(res => {
            $('#storageOrgUnitAdd,#inStorageOrgUnitAdd').empty().select2({
                placeholder: '请选择工厂...', //默认文字提示
                language: "zh-CN", //汉化
                allowClear: true, //允许清空
                data: res.map(item => {
                    return {
                        id: item.id,
                        text: `${item.name}(${item.numCode})`,
                        name: item.name
                    }
                }),
            });
            $('#storageOrgUnitAdd,#inStorageOrgUnitAdd').setSelectValue();
        });
        // 仓库
        await requestDict(DictionaryType.INVTRYLOCATION_TYPE).then(res => {
            $('#warehouseAdd,#inWarehouseAdd').empty().select2({
                placeholder: '请选择仓库...', //默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,//允许清空
                data: res.data.map(item => {
                    return {
                        id: item.value,
                        text: item.displayName
                    }
                }),
            });
            $('#warehouseAdd,#inWarehouseAdd').setSelectValue();
        });
        // 移动类型
        await requestDict(DictionaryType.CONSUMING_TYPE).then(res => {
            res.data.forEach(item => {
                conumingInfo[item.value] = item.displayName;
            });
            let idup = getUrlKey("id");
            if(idup){
                $('#bTypeAdd').empty().select2({
                    placeholder: '请选择移动类型...', //默认文字提示
                    language: "zh-CN",//汉化
                    allowClear: true,//允许清空
                    data: res.data.map(item => {
                        return {
                            id: item.value,
                            text: item.displayName
                        }
                    }),
                });
            }else{
                let newList = res.data.filter(s=>s.value==2||s.value==4);
                $('#bTypeAdd').empty().select2({
                    placeholder: '请选择移动类型...', //默认文字提示
                    language: "zh-CN",//汉化
                    allowClear: true,//允许清空
                    data: newList.map(item => {
                        return {
                            id: item.value,
                            text: item.displayName
                        }
                    }),
                });
            }
            $('#bTypeAdd').setSelectValue();
            _initCommand();
        });

    });

    // 初始化数据
    const _initCommand = async () => {
        //下拉框监听事件
        $('#bTypeAdd').on('select2:select', function (e) {
            _vm.bType = $(this).val();
        })
        //下拉框监听事件
        $('#storageOrgUnitAdd').on('select2:select', function (e) {
            _vm.storageOrgUnit.id = $(this).select2('data')[0].id;
            _vm.storageOrgUnit.name = $(this).select2('data')[0].name;
            _vm.storageOrgUnit.code = $(this).select2('data')[0].numCode;
            $('#inBreedBatchId').prop('disabled', false);
            _select2BreedBatch(`#inBreedBatchId`, $(this).val(), '', '请选择领用批次...');
            let data = e.params.data; // 获取选中项的数据
            let text = data.text; // 获取选中项的文本
            let textshow = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(textshow);
        }).on('select2:clear', function () {
            $('#inBreedBatchId').prop('disabled', true);
            $('#inBreedBatchId').empty().setSelectValue();
        })
        //下拉框监听事件
        $('#inStorageOrgUnitAdd').on('select2:select', function (e) {
            _vm.inStorageOrgUnit.id = $(this).select2('data')[0].id;
            _vm.inStorageOrgUnit.name = $(this).select2('data')[0].name;
            _vm.inStorageOrgUnit.code = $(this).select2('data')[0].numCode;
            let data = e.params.data; // 获取选中项的数据
            let text = data.text; // 获取选中项的文本
            let textshow = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(textshow);
        })
        //下拉框监听事件
        $('#warehouseAdd').on('select2:select', function (e) {
            _vm.warehouse.id = $(this).select2('data')[0].id;
            _vm.warehouse.name = $(this).select2('data')[0].text;
            _vm.warehouse.code = $(this).select2('data')[0].id;
            let data = e.params.data; // 获取选中项的数据
            let text = data.text; // 获取选中项的文本
            let textshow = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(textshow);
        })
        //下拉框监听事件
        $('#inWarehouseAdd').on('select2:select', function (e) {
            _vm.inWarehouse.id = $(this).select2('data')[0].id;
            _vm.inWarehouse.name = $(this).select2('data')[0].text;
            _vm.inWarehouse.code = $(this).select2('data')[0].id;
            let data = e.params.data; // 获取选中项的数据
            let text = data.text; // 获取选中项的文本
            let textshow = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(textshow);
        })
        //下拉框监听事件
        $('#inBreedBatchId').on('select2:select', function (e) {
            _vm.breedBatch.id = $(this).select2('data')[0].id;
            _vm.breedBatch.name = $(this).select2('data')[0].name;
            let data = e.params.data; // 获取选中项的数据
            let text = data.text; // 获取选中项的文本
            let textshow = cutstr(text, 20); // 截取字符串
            $(this).select2('val', data.id); // 假设您想根据ID设置选中值
            $(this).next('.select2-container').find('.select2-selection__rendered').text(textshow);
        })

        $("#informationSubmit").text("保存");
        let idup = getUrlKey("id");
        _vm.idup = idup;
        if (Utils.IsNotNull(idup)) {
            _vm.isShowAddEntry = false;
            let materialreqInfo = await materialreqbillsApi.getmaterialreqBill(idup)
            const propertiesToCopy = ['bizDate', 'remark', 'bType', 'storageOrgUnit', 'warehouse', 'breedBatch', 'entries', 'inStorageOrgUnit', 'inWarehouse'];
            propertiesToCopy.reduce((obj, prop) => {
                _vm[prop] = materialreqInfo[prop];
            }, {});
            _vm.bizDate = moment(materialreqInfo.bizFormObj?.bizDate).format('YYYY-MM-DD')
            const editJson = propertiesToCopy.reduce((obj, prop) => {
                obj[prop] = _vm[prop];
                return obj;
            }, {});
            materialreqInfo.entries.forEach((item, index) => {
                item.seq = index;
            })
            // 存储主表/分录
            Utils.SetSessionStorage("deliverDatas", editJson)
            Utils.SetSessionStorage("getEntryInfo", materialreqInfo.entries)
        } else {
            _vm.isShowAddEntry = true;
        }

        // 获取主表数据
        let getMainInfo = JSON.parse(Utils.GetSessionStorage("deliverDatas"))
        if (Utils.IsNotNull(getMainInfo)) {
            var storageOrgUnitName = cutstr(getMainInfo.storageOrgUnit.name, 20); // 截取字符串
            var warehouseName = cutstr(getMainInfo.warehouse.name, 20); // 截取字符串
            var inStorageOrgUnitName = cutstr(getMainInfo.inStorageOrgUnit.name, 20); // 截取字符串
            var inWarehouseName = cutstr(getMainInfo.inWarehouse.name, 20); // 截取字符串
            var breedBatchName = cutstr(getMainInfo.breedBatch.name, 20); // 截取字符串
            const propertiesToCopy = [
                'bizDate', 'remark', 'bType', 'storageOrgUnit', 'warehouse', 'breedBatch', 'entries', 'inStorageOrgUnit', 'inWarehouse'
            ];
            propertiesToCopy.reduce((obj, prop) => {
                _vm[prop] = getMainInfo[prop];
            }, {});
            $('#storageOrgUnitAdd').setSelectValue(getMainInfo.storageOrgUnit.id, storageOrgUnitName)
            $('#warehouseAdd').setSelectValue(getMainInfo.warehouse.id || getMainInfo.warehouse.code, warehouseName || getMainInfo.warehouse.code)
            $('#inStorageOrgUnitAdd').setSelectValue(getMainInfo.inStorageOrgUnit.id, inStorageOrgUnitName)
            $('#inWarehouseAdd').setSelectValue(getMainInfo.inWarehouse.id || getMainInfo.inWarehouse.code, getMainInfo.inWarehouse.code || getMainInfo.inWarehouse.name)
            $('#bTypeAdd').val(getMainInfo.bType).trigger('change');
            if (getMainInfo.bType == 3 && !(getMainInfo.inStorageOrgUnit.id) && !(getMainInfo.inWarehouse.code)) {
                $('#inStorageOrgUnitAdd').setSelectValue(getMainInfo.storageOrgUnit.id, getMainInfo.storageOrgUnit.name);
                $('#inWarehouseAdd').setSelectValue(getMainInfo.warehouse.id || getMainInfo.warehouse.code, getMainInfo.warehouse.code || getMainInfo.warehouse.name);
                $('#storageOrgUnitAdd').setSelectValue('');
                $('#warehouseAdd').setSelectValue('');
            }
            _select2BreedBatch(`#inBreedBatchId`, getMainInfo.storageOrgUnit.id, { "id": getMainInfo.breedBatch.id, "name": breedBatchName }, '请选择领用批次...');
            if(_vm.idup){ // 编辑
                if (getMainInfo.bType == 0 || getMainInfo.bType == 3 || getMainInfo.bType == 4) {
                    $('#inBreedBatchId').attr('disabled', false)
                }
                else {
                    $('#inBreedBatchId').attr('disabled', true)
                }
                $('#inStorageOrgUnitAdd,#storageOrgUnitAdd,#warehouseAdd,#inWarehouseAdd,#bTypeAdd,#bizDateAdd').prop('disabled', true);
                $('#bizDateAdd').css('background-color','#F3F7F9');
            }else{
                $('#bizDateAdd').css('background-color','white');
                $('#inStorageOrgUnitAdd,#storageOrgUnitAdd,#warehouseAdd,#inWarehouseAdd,#bTypeAdd,#bizDateAdd,#inBreedBatchId').prop('disabled', false);
            }
            
        }
        // 获取分录数据
        let getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        if (getEntryInfo) {
            if(_vm.idup){ // 编辑
                getEntryInfo.forEach((item, index) => {
                    item.editEntry = 'none';
                })
            }else{
                getEntryInfo.forEach((item, index) => {
                    item.editEntry = 'block';
                })
            }
            $('#salesEntry').empty().append(addsaleTemplate(getEntryInfo));
        }

        // 选择业务日期
        $('#search-date').on('click', function () {
            pick();
        });

        // 点击 新增分录
        $('#add-entries').on("click", function (e) {
            // 存储数据
            storeSession();
            let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.length || 0;
            location.href = `../materialreqbills/materialreqbillsentry.html?index=${index}`;
        });

        // 点击 编辑分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit-recev]', function () {
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            let index = $(this).data('index')
            location.href = `../materialreqbills/materialreqbillsentry.html?index=${index}&isEdit=true`;
        });

        // 点击 删除分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete-recev]', function () {
            let seq = $(this).data('index')
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
                buttons: [
                    {
                        text: "取消", className: "default", onClick: function () {
                            $.closeModal();
                        }
                    },
                    {
                        text: "确定", onClick: function () {
                            if (!getEntryInfo) {
                                getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"));
                            }
                            let datas = getEntryInfo.filter(item => item.seq != seq)
                            // 重新排序
                            let info = datas.map((item, index) => {
                                item.seq = index
                                return item
                            }) || []
                            // 赋值 
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", info))
                            $('#salesEntry').empty().append(addsaleTemplate(info));
                            $.closeModal();
                        }
                    }
                ]
            });
        });

    }
    // 操作函数
    const clickFun = () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            window.sessionStorage.removeItem("getEntryInfo");
            window.sessionStorage.removeItem("deliverDatas");
            location.href = `../materialreqbills/materialreqbillslist.html?v=${Utils.GetTime()}`;
        });

        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../materialreqbills/materialreqbillslist.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddmatrrialreq', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                'bottom': '-6rem',
                'transition': 'all .ls ease-in'
            });
        });

        // 提交数据
        $('#informationSubmit').on("click", function (e) {
            if (!Utils.IsNotNull(_vm.bType) && _vm.bType!=0) {
                return $.toptip(`请选择移动类型!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.breedBatch.id)) {
                return $.toptip(`请选择领用批次!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.storageOrgUnit.id)) {
                return $.toptip(`请选择调出工厂!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.warehouse.id)) {
                return $.toptip(`请选择调出仓库!`, 'warning');
            }
            if(_vm.bType==2 || _vm.bType==4){
                if (!Utils.IsNotNull(_vm.inStorageOrgUnit.id)) {
                    return $.toptip(`请选择调入工厂!`, 'warning');
                }
                if (!Utils.IsNotNull(_vm.inWarehouse.id)) {
                    return $.toptip(`请选择调入仓库!`, 'warning');
                }
                let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo")) || [];
                if (!entries.length) {
                    return $.toptip(`请新增分录!`, 'warning');
                }
            }
            savetips();
        })
    }
    // 保存
    const savetips = () => {
        let tiptext = '是否确认保存该单据？'
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" >${tiptext}</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        $.closeModal();
                        const propertiesToCopy = ['bizDate', 'remark', 'bType', 'storageOrgUnit', 'warehouse', 'inStorageOrgUnit', 'inWarehouse', 'breedBatch', 'entries'];
                        const addJson = propertiesToCopy.reduce((obj, prop) => {
                            obj[prop] = _vm[prop];
                            return obj;
                        }, {});
                        let idup = _vm.idup;
                        let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
                        addJson.entries = [...entries]

                        if (Utils.IsNotNull(idup)) {
                            return materialreqbillsApi.updatematerialreqBill(idup, JSON.stringify(addJson)).then(res => {
                                $.toptip('请求成功。', 'success');
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getEntryInfo");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    location.href = `../materialreqbills/materialreqbillslist.html?v=${Utils.GetTime()} `;
                                }, 1000);
                            })
                        } else {
                            materialreqbillsApi.addmaterialReq(addJson).then(res => {
                                $.toptip('请求成功!', 'success');
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getEntryInfo");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    location.href = `./materialreqbillslist.html `;
                                }, 1000);
                            }, err => {
                                $.toptip(err.responseJSON?.msg, 'error');
                            });
                        }
                    }
                }
            ]
        });
    }

    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    // 日期选择器
    const pick = () => {
        weui.datePicker({
            defaultValue: (moment(new Date()).format('YYYY-MM-DD')).split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                _vm.bizDate = moment(new Date(value)).format('YYYY-MM-DD')
            }
        });
    }

    //TODO : 查询养殖批次信息
    const _select2BreedBatch = (id, farmId, json, title) => {
        Select2Page($(id), `${Utils.CurDomain.BaseCfgUrl}/breedbatchs/rlist`, (params) => {
            return JSON.stringify({
                farmOrgName: '',
                tags: '',
                name: params.term,
                sort: '',
                isEnd: false,
                farmOrgId: farmId || '',
                pageSize: 20,
                pageIndex: (params.page || 1) - 1
            })
        }, "POST", {
            allowClear: true,//允许清空
            placeholder: title,
            templateResult: function (res) {
                return `${res.name}`;
            }
        });
        //编辑回显
        if (Utils.IsNotNull(json)) {
            $(id).setSelectValue(json.id, json.name);
        }
    }

    // 保存分录以上的内容
    const storeSession = () => {
        const propertiesToCopy = [
            'bizDate', 'remark', 'bType', 'storageOrgUnit', 'warehouse', 'breedBatch', 'entries', 'inStorageOrgUnit', 'inWarehouse'
        ];
        const deliverDatas = propertiesToCopy.reduce((obj, prop) => {
            obj[prop] = _vm[prop];
            return obj;
        }, {});
        Utils.SetRouterState('deliverDatas', deliverDatas)
    }

    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }

})(window, document, jQuery)